import {
  Avatar,
  Button,
  Card,
  Col,
  Empty,
  Form,
  Input,
  List,
  message,
  Row,
  Space,
  Spin,
  Tooltip,
} from 'antd';
import { AnnounceManageAPI } from '../common/type';
import pageStyles from '@/common/pageLayout.less';
import { getAnnounceDataSercvice } from '../service';
import { useContext, useEffect, useState } from 'react';
import { getKeyRouter, getUserID } from '@/utils';
import InfiniteScroll from 'react-infinite-scroller';
import { SyncOutlined, SoundOutlined } from '@ant-design/icons';
import moment from 'moment';
import { AnnounceUpdateContext } from '../common/UpdateContext';
// const InfiniteScrollNew: any = InfiniteScroll
import { history } from 'umi';
import cls from 'classnames';

export const UpdateViewRight: React.FC<AnnounceManageAPI.IUpdateViewRight> = () => {
  const {
    curRes,
    dispatch,
    prefixCls,
    leftSelectRows,
    announceInfo,
    leftSelectKeys,
    locationProps,
    reloadAnnounceInfo,
  } = useContext(AnnounceUpdateContext);

  /**
   * 传入接口参数
   */
  const [creterPayload, setCreterPayload] = useState<any>({
    params: 'createrID',
    createrID: getUserID(),
  });

  const [isOnReload, setIsOnReload] = useState<boolean>(false);

  /**
   * 保存的分页参数
   */
  const [scrollObj, setScrollObj] = useState<any>({
    total: 0,
    count: 0,
    loading: false,
    hasMore: true,
    limit: 10,
  });

  /**
   *  保存 搜索框的数据
   */
  const [searchValue, setSearchValue] = useState<string>();

  /**
   * 保存查询的数据
   */
  const [myCompileData, setMyCompileData] = useState<Record<string, any>[]>([]);

  /**
   * 获取我的编撰回调
   * @param res
   */
  const getAnnounceDataCallllback = (res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    } else {
      setMyCompileData(res?.rows);
      setScrollObj({
        ...scrollObj,
        loading: false,
        total: res.total,
      });
    }
    setIsOnReload(false);
  };

  /**
   * 引入获取我的编撰接口
   */
  const {
    getAnnounceDataRun,
    getAnnounceDataLoading,
  } = getAnnounceDataSercvice(getAnnounceDataCallllback);

  /**
   * 初始化获取数据
   */
  const defaultGetAnnounce = () => {
    let { count, limit } = scrollObj;
    count++;
    setScrollObj({
      ...scrollObj,
      count: count,
      loading: true,
    });
    let payload = {
      ...creterPayload,
      page: 1,
      rows: count * 10 + limit,
    };
    getAnnounceDataRun(payload);
  };

  useEffect(() => {
    defaultGetAnnounce();
  }, []);

  /**
   * 处理超过多少字的tooltip
   */
  const handleTooltip = (str: string) => {
    let newStr: string = str;
    if (str && str?.length > 50) {
      newStr = str.substr(0, 50) + '...';
    }
    return newStr;
  };

  /**
   * 处理滚动加载
   */
  const handleInfiniteOnLoad = () => {
    const { total } = scrollObj;
    if (myCompileData?.length >= total) {
      message.warning('没有更多数据了哦');
      setScrollObj({
        ...scrollObj,
        hasMore: false,
        loading: false,
      });
      return;
    }
    defaultGetAnnounce();
  };

  /**
   * 刷新
   */
  const reloadRight = () => {
    setScrollObj({
      ...scrollObj,
      count: 0,
    });
    setSearchValue('');
    setIsOnReload(true);
  };

  useEffect(() => {
    if (scrollObj?.count == 0 && isOnReload) {
      defaultGetAnnounce();
    }
  }, [scrollObj?.count, isOnReload]);

  /**
   * 跳转详情页面
   * @param resObj
   */
  const gotoAnnounceDetail = (resObj: any) => {
    history.push({
      pathname: `/announceController/getAnnounceByID/:${getKeyRouter()}${getKeyRouter()}`,
      state: {
        id: resObj?.id,
      },
    });
  };

  return (
    <Card
      title={'我的编撰'}
      className={cls(pageStyles['page-view'], prefixCls + 'CardRightSearch')}
      bodyStyle={{
        height: '95%',
        padding: '5px 0px',
        overflow: 'hidden',
      }}
      extra={
        <Space>
          <div>
            <Input
              placeholder="按标题搜索"
              value={searchValue}
              onChange={(e) => {
                setSearchValue(e?.target?.value);
              }}
              onPressEnter={() => {
                let payload: any = {
                  ...creterPayload,
                  ...scrollObj,
                  announceTitle: searchValue,
                };
                getAnnounceDataRun(payload);
              }}
            />
          </div>
          <Button
            icon={<SyncOutlined />}
            type="primary"
            size="small"
            onClick={reloadRight}
          />
        </Space>
      }
    >
      <Spin spinning={getAnnounceDataLoading}>
        <div className={pageStyles['InfiniteScrollView']}>
          <InfiniteScroll
            loadMore={handleInfiniteOnLoad}
            initialLoad={false}
            pageStart={1}
            useWindow={false}
            hasMore={!scrollObj?.loading && scrollObj?.hasMore}
          >
            {myCompileData && myCompileData?.length > 0 ? (
              <div
                className={cls(
                  prefixCls + 'rightCompileStyle',
                  'compile-avatar',
                )}
              >
                <List
                  itemLayout="horizontal"
                  dataSource={myCompileData}
                  renderItem={(item) => (
                    <List.Item>
                      <List.Item.Meta
                        avatar={
                          <div>
                            <Avatar size="large" icon={<SoundOutlined />} />
                          </div>
                        }
                        title={
                          <Tooltip
                            placement="topLeft"
                            title={handleTooltip(item.announceTitle)}
                          >
                            <a
                              onClick={() => {
                                gotoAnnounceDetail(item);
                              }}
                              style={{
                                maxWidth: '95%',
                                display: 'block',
                                float: 'none',
                              }}
                              className={pageStyles['over-flow-hidden']}
                            >
                              {item.announceTitle}
                            </a>
                          </Tooltip>
                        }
                        description={
                          <Tooltip
                            placement="topLeft"
                            title={handleTooltip(
                              item?.announceContent?.contentText,
                            )}
                          >
                            <div
                              onClick={() => {
                                gotoAnnounceDetail(item);
                              }}
                            >
                              <Row>
                                <div
                                  style={{ maxWidth: '95%' }}
                                  dangerouslySetInnerHTML={{
                                    __html: item?.announceContent?.contentText,
                                  }}
                                  className={pageStyles['over-flow-hidden']}
                                />
                              </Row>
                              <Row>
                                <div
                                  style={{
                                    textAlign: 'right',
                                    width: '100%',
                                    marginTop: '4px',
                                    fontSize: '12px',
                                  }}
                                >
                                  {moment(item.createTime).format('YYYY-MM-DD')}
                                </div>
                              </Row>
                            </div>
                          </Tooltip>
                        }
                      />
                    </List.Item>
                  )}
                />
                {scrollObj?.loading && scrollObj?.hasMore && (
                  <div>
                    <Spin />
                  </div>
                )}
              </div>
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </InfiniteScroll>
        </div>
      </Spin>
    </Card>
  );
};
